﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;
using System.Globalization;

namespace Whoever.Patterns.Website2.ModelBinder
{
	public class DateTimeModelBinder : IModelBinder
	{
		public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			var valueResult = bindingContext.ValueProvider
				.GetValue(bindingContext.ModelName);

			ModelState modelState = new ModelState { Value = valueResult };

			object actualValue = null;

			try
			{
				actualValue = DateTime.ParseExact(valueResult.AttemptedValue.Trim(), "mm/dd/yyyy", CultureInfo.InvariantCulture);
			}
			catch (FormatException e)
			{
				modelState.Errors.Add(e);
			}

			bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
			return actualValue;
		}
	}
}